import sys

from QtUi.mainUi import Ui_MainWindow  #导入QTdesigner的样式设计
from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog, QVBoxLayout, QWidget, QPushButton, QSizePolicy,QHBoxLayout,QLabel
from PyQt6.QtMultimedia import QMediaPlayer
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtGui import QImage, QPixmap
import cv2
from ultralytics import YOLO
from collections import defaultdict
import time
from PyQt6.QtCore import QCoreApplication



class MyForm(QMainWindow,Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.mediaPlayer = QMediaPlayer(self)
        # 使用setVideoOutput方法
        # self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.video_label = QLabel(self)
        self.video_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        #self.video_label.setPixmap(QPixmap("images/03.jpg"))
        # 设置固定大小
        self.video_label.setFixedSize(200, 300)  # 例如，设置为800x600像素

        # 按钮打开文件
        self.selectButton.clicked.connect(self.openVideoFile)
        # 播放按钮
        self.payButton.clicked.connect(self.playVideo)
        #暂停按钮
        self.pauseButton.clicked.connect(self.pauseVideo)
        #内容输出
        self.listWidget.addItem("Item 1")
        self.model = YOLO('yolov8n.pt')

        self.pixmap = QPixmap()  # 初始化 QPixmap 对象


    def openVideoFile(self):
        try:
            video_path, _ = QFileDialog.getOpenFileName(self, "打开视频文件", "",
                                                      "Video Files (*.mp4 *.avi *.mkv);;All Files (*)")
            if video_path:
                #media=QUrl.fromLocalFile(video_path)
                cap = cv2.VideoCapture(video_path)
                if cap.isOpened():
                    # 从视频中读取一帧
                    success, frame = cap.read()
                    if success:
                        # 在该帧上运行YOLOv8推理
                        results = self.model(frame)
                        # 在帧上可视化结果
                        annotated_frame = results[0].plot()
                        self.display_frame(annotated_frame)
                        #time.sleep(0.033)  # 添加延迟，以使图像不会太快刷新 (33毫秒)
                        # self.mediaPlayer.setSource(annotated_frame)
                        # self.mediaPlayer.play()
        except Exception as e:
            print(f"发生异常: {e}")

    def playVideo(self):
        self.mediaPlayer.play()

    def pauseVideo(self):
        self.mediaPlayer.pause()

    def display_frame(self, frame):
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        height, width, channel = rgb_frame.shape
        bytes_per_line = 3 * width

        pixmap = QPixmap.fromImage(QImage(rgb_frame.data, width, height, bytes_per_line, QImage.Format.Format_RGB888))
        pixmap = pixmap.scaled(self.video_label.size(), Qt.AspectRatioMode.KeepAspectRatio)

        self.video_label.setPixmap(pixmap)
        #self.video_label.setPixmap(QPixmap("images/03.jpg"))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    my_form = MyForm()
    my_form.setWindowTitle('Yolov8')
    my_form.show()
    sys.exit(app.exec())